package com.lmk.filter;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;

@Component
public class LoginFilter extends ZuulFilter {
    /*过滤器类型*/
    @Override
    public String filterType() {
        return "pre";// 前置
    }
    /*过滤顺序*/
    @Override
    public int filterOrder() {
        return 0;
    }
    /*判断请求的资源是否为公共资源，来判断是否执行run方法*/
    @Override
    public boolean shouldFilter() {
        // 获取当前请求路径
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        String requestURL = request.getRequestURI();
        // 判断请求地址中是否有login或register
        if (requestURL.endsWith("login") || requestURL.endsWith("register")){
            return false;
        }
        return true;
    }
    /*判断请求头中是否有token*/
    @Override
    public Object run() throws ZuulException {
        // 获取请求的token
        RequestContext currentContext = RequestContext.getCurrentContext();
        String token = currentContext.getRequest().getHeader("token");

        HttpServletResponse response = RequestContext.getCurrentContext().getResponse();
        response.setContentType("application/json;charset=utf-8");
        if (!StringUtils.hasLength(token)){
            try {
                // 1.设置响应内容
                PrintWriter writer = response.getWriter();
                HashMap<String, Object> map = new HashMap<>();
                map.put("success", false);
                map.put("message", "请登录！");
                String data = JSON.toJSONString(map);
                writer.write(data);
                // 2.阻止后续filter执行
                RequestContext.getCurrentContext().setSendZuulResponse(false);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
